#include "exampleservice.h"

#include <fstream>
#include <random>

#include <core/eventloop.h>

using namespace ut;
using namespace std;

ExampleService::ExampleService(Connection &conn, const ut::Path &path)
    : ObjectAdaptor(conn, path)
{
    Opacity = 1.0;
}

int32_t ExampleService::Random()
{
    random_device device;
    ranlux48 engine(device());
    // generate a random int range 0 ~ 100
    uniform_int_distribution<> dist(0, 100);
    return dist(engine);
}

string ExampleService::Hello(const string &name)
{
    return "hello " + name;
}

Variant ExampleService::Echo(const Variant &input)
{
    return Variant();
}

vector<uint8_t> ExampleService::Cat(const string &file)
{
    vector<uint8_t> bytes;

    ifstream fin;
    fin.open(file, ios::in);

    // open file error
    if (fin.fail())
        return bytes;

    assert(fin.is_open());

    char c;
    while ((c = fin.get()) != EOF)
        bytes.push_back(c);

    return bytes;
}

int32_t ExampleService::Sum(const vector<int32_t> &ints)
{
    // assure that the sum won't overflow
    int32_t sum = 0;

    for (auto e : ints)
        sum += e;

    return sum;
}

map<string, string> ExampleService::Info()
{
    map<string, string> m;

    m["Version"] = "0.0.9";
    m["PkgName"] = "udcp-dev-bunble";
    m["BuildSystem"] = "CMake";
    m["Company"] = "Uniontech";

    return m;
}

void ExampleService::Exit()
{
    EventLoop::current_eventloop()->quit();
}

void ExampleService::on_set_property(InterfaceAdaptor &interface, const string &prop, const Variant &value)
{
    // 发送 OpacityChanged 信号
    OpacityChanged((double)value);
}
